package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"library/library/internal/svc"
	"library/library/library"
	"library/models/cache"
	"library/models/mysql"
	"library/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *library.UpdatePasswordRequest) (*library.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Where("account = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册")
	}

	user = mysql.User{
		Model:    gorm.Model{ID: user.ID},
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("密码找回失败")
	}

	return &library.UpdatePasswordResponse{UserId: int64(user.ID)}, nil
}
